//
//  LoginViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/29.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class LoginViewController: BaseViewController, MBProgressHUDDelegate {
    
    var icon: UIImageView!
    var phoneField: FUITextField!
    var passwordField: FUITextField!
    var button: FUIButton!
    
    var phoneNum: String!
    var passwordNum: String!
    
    var hud: MBProgressHUD!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "登录"
        #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE
            self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "注册", style: UIBarButtonItemStyle.plain, target: self, action: #selector(LoginViewController.sign))
        #endif
        
        InitViews()
    }
    
    func sign(){
        let signVC = PhoneNumViewController()
        self.navigationController?.pushViewController(signVC, animated: true)
    }
    
    /**
     初始化各控件
     */
    func InitViews() {
        
        icon = UIImageView.init(frame: CGRect(x: (screenW - 66)/2, y: 120, width: 66, height: 81))
        icon.contentMode = UIViewContentMode.scaleAspectFit
        icon.image = logo
        
        phoneField = FUITextField.init(frame: CGRect(x: 20, y: icon.frame.maxY + 50, width: screenW - 40, height: 40))
        phoneField.backgroundColor = UIColor.clear
        phoneField.textFieldColor = UIColor.white
        phoneField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        phoneField.layer.borderWidth = 1.0
        phoneField.layer.cornerRadius = 3.0
        phoneField.borderColor = barColor
        phoneField.borderWidth = 2.0
        phoneField.cornerRadius = 3.0
        phoneField.font = UIFont.systemFont(ofSize: 16)
        phoneField.edgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
        phoneField.placeholder = "请输入手机号码"
        phoneField.keyboardType = UIKeyboardType.phonePad
        
        passwordField = FUITextField.init(frame: CGRect(x: 20, y: phoneField.frame.maxY + 10, width: screenW - 40, height: 40))
        passwordField.backgroundColor = UIColor.clear
        passwordField.textFieldColor = UIColor.white
        passwordField.layer.borderColor = UIColor.init(hexString: "f0f0f0", alpha: 1.0).cgColor
        passwordField.layer.borderWidth = 1.0
        passwordField.layer.cornerRadius = 3.0
        passwordField.borderColor = barColor
        passwordField.clearButtonMode = UITextFieldViewMode.whileEditing
        passwordField.borderWidth = 2.0
        passwordField.cornerRadius = 3.0
        passwordField.font = UIFont.systemFont(ofSize: 16)
        passwordField.edgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 8.0)
        passwordField.placeholder = "请输入用户密码"
        passwordField.isSecureTextEntry = true
        
        button = FUIButton.init(frame: CGRect(x: 20, y: passwordField.frame.maxY + 10, width: screenW - 40, height: 40))
        button.buttonColor = barColor
        button.shadowColor = barColor
        button.shadowHeight = 3.0
        button.cornerRadius = 6.0
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        button.setTitle("登录", for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState.highlighted)
        button.addTarget(self, action: #selector(LoginViewController.LoginClick), for: UIControlEvents.touchDown)
        
        self.view.addSubview(icon)
        self.view.addSubview(phoneField)
        self.view.addSubview(passwordField)
        self.view.addSubview(button)
        
    }
    
    func LoginClick() {
        passwordNum = passwordField.text
        phoneNum = phoneField.text
        
        if isPhoneNum(phoneNum) && passwordNum.characters.count != 0 {
            LoginTask(phoneNum, password: passwordNum)
        }else {
            TSMessage.showNotification(in: self, title: "提示", subtitle: "请输入正确的手机号码和用户密码", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
        }
    }
    
    /**
     异步任务登陆
     
     XmlNode usertelxml = ndoc.SelectSingleNode("//rss/channel/tel");
     XmlNode userpwdxml = ndoc.SelectSingleNode("//rss/channel/pwd");
     
     - parameter phone:    手机号码
     - parameter password: 用户密码
     */
    func LoginTask(_ phone: String!, password: String!) {
        hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.mode = MBProgressHUDMode.indeterminate
        hud.labelText = "正在登陆中...请稍后"
        
        //1230 - 管家和超管的登录接口判断修改
        /*
         * 1、管家登录接口
         * 接口地址：UserLogin.ashx?t=2
         * 参数:
         * XmlNode usertelxml = ndoc.SelectSingleNode("//rss/channel/tel")
         * XmlNode userpwdxml = ndoc.SelectSingleNode("//rss/channel/pwd")
         * 
         * 2、超管登录接口
         * 接口地址：UserLogin.ashx?t=3
         * 参数:
         * XmlNode usertelxml = ndoc.SelectSingleNode("//rss/channel/tel")
         * XmlNode userpwdxml = ndoc.SelectSingleNode("//rss/channel/pwd")
         *
         */
        /*
        //1230 - 修改之后
        
        var requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>2</t><tel>" + phone + "</tel><pwd>" + password + "</pwd></channel></rss>"
        var url = server + userLogin
        
        #if BELLSUPER || HSSUPER || TXSUPER
            
            requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>3</t><tel>" + phone + "</tel><pwd>" + password + "</pwd></channel></rss>"
            url = server + userLogin
            
        #endif
         */
        
        //1230 -  修改之前
        var requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>36</t><tel>" + phone + "</tel><pwd>" + password + "</pwd></channel></rss>"
        var url = server + adminwebapppi
        #if BELLSUPER || HSSUPER || TXSUPER
            requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>1</t><tel>" + phone + "</tel><pwd>" + password + "</pwd></channel></rss>"
            url = server + superWebapp
        #endif
    
        
        
        
        
        HttpPostUTF(url, requestXML: requestXML, finished: { (data, result, error) in
            
            /*
            //1230 - 登录接口变之后
            if error == nil {
                let json = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                let code = json.dictionaryValue["code"]
                
                if code == "1" {
                    //用户名不存在、请先注册
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "用户名不存在、请先注册！", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                    
                }else if code == "2" {
                    //用户名或密码错误、请重新登录
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "用户名或密码错误、请重新登录！", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                }else if code == "200" {
                    //正确返回
                    #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE
                        let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["result"]["post"]
                        if array.count != 0 {
                            for i in 0..<array.count {

                                let dic = array[i]
                                let username = dic["UserName"].stringValue
                                let usertype = dic["ProName"].stringValue
                                let schid = dic["SchSerid"].stringValue
                                let userid = dic["UserSerID"].stringValue
                                let schname = dic["SchName"].stringValue
                                let doname = dic["imgurl"].stringValue
                                let pluglist = dic["pluglist"]
                                
                                let defaults = UserDefaults.standard
                                let user = UserPojo()
                                user.userphone = phone
                                user.userpassword = password
                                user.username = username
                                user.usertype = usertype
                                user.schid = schid
                                user.userid = userid
                                user.schname = schname
                                user.doname = doname
                                
                                defaults.set(user.userphone!, forKey: "userphone")
                                defaults.set(user.userpassword!, forKey: "password")
                                defaults.set(user.userid!, forKey: "userid")
                                defaults.set(user.username!, forKey: "username")
                                defaults.set(user.usertype!, forKey: "usertype")
                                defaults.set(user.schid!, forKey: "schid")
                                defaults.set(user.schname!, forKey: "schname")
                                defaults.set(user.doname!, forKey: "doname")
                                defaults.synchronize()
                                
                                initLocationData()
                                
                                let rightArray = NSMutableArray()
                                if pluglist.count != 0 {
                                    rightArray.addObjects(from: pluglist.arrayObject!)
                                }
                                
                                setRightArray(rightArray)
                                
                                #if EDUMANAGE
                                    
                                    let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                    myDelegate.goToMain()
                                    
                                #elseif HSEDUMANAGE || TXEDUMANAGE
                                    
                                    let officeUrl = server + adminofficewebappapi
                                    let officeRequest = requestHeader + "1</t><schid>" + user.schid + "</schid><userid>" + user.userid + "</userid><usertype>T</usertype></channel></rss>"
                                    HttpPostUTF(officeUrl, requestXML: officeRequest, finished: { (data, result, error) in
                                        
                                        if error == nil {
                                            let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                                            let officeRightArray = NSMutableArray()
                                            
                                            if array.count != 0 {
                                                officeRightArray.addObjects(from: array.arrayObject!)
                                            }
                                            
                                            setOfficeRightArray(officeRightArray)
                                            
                                            let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                            myDelegate.goToMain()
                                            
                                        }else {
                                            UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                                            self.hud.hide(true)
                                        }
                                        
                                        
                                    })
                                
                                #endif
                                
                            }
                        }
                        
                        
                    #elseif BELLSUPER || HSSUPER || TXSUPER
                        let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["result"]
                        if array.count != 0 {
                            for i in 0..<array.count {
                                
                                let dic = array[i]
                                
                                let defaults = UserDefaults.standard
                                let user = UserPojo()
                                user.userphone = phone
                                user.userpassword = password
                                user.username = dic["TrueName"].stringValue
                                user.schid = dic["SchSerID"].stringValue
                                user.userid = dic["TeaSerID"].stringValue
                                user.UpperCode = dic["UpperCode"].stringValue
                                user.SupperType = dic["SuperType"].stringValue
                                
                                defaults.set(user.userphone!, forKey: "userphone")
                                defaults.set(user.userpassword!, forKey: "password")
                                defaults.set(user.userid!, forKey: "userid")
                                defaults.set(user.username!, forKey: "username")
                                defaults.set(user.schid!, forKey: "schid")
                                defaults.set(user.UpperCode, forKey: "UpperCode")
                                defaults.set(user.SupperType, forKey: "SupperType")
                                defaults.set("", forKey: "doname")
                                defaults.synchronize()
                                
                                let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                myDelegate.goToSuper()
                                
                            }
                        }
                    #endif
                    
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                    self.hud.hide(true)
                }
                
            }
            
            //+++++++++++++++++
            */
            
            
            //1230 - 登录接口变之前
            
            if error == nil {

                if result == "false" {
                    /**
                     用户不存在
                     */
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "对不起，该手机号码尚未绑定", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                }else if result == "手机号或密码不正确" {
                    /**
                     用户名密码不正确
                     */
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "用户名，密码不正确", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                }else if (result?.hasPrefix("\"<!DOCTYPE html>"))!{
                    /**
                     接口错误
                     */
                    TSMessage.showNotification(in: self, title: "提示", subtitle: "对不起，获取数据产生错误，请联系管理员！", image: nil, type: TSMessageNotificationType.error, duration: 1.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                    self.hud.hide(true)
                    
                }else {
                    #if EDUMANAGE || HSEDUMANAGE || TXEDUMANAGE
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)["post"]
                    if array.count != 0 {
                        for i in 0..<array.count {
                            
                            
                            let dic = array[i]
                            let username = dic["UserName"].stringValue
                            let usertype = dic["ProName"].stringValue
                            let schid = dic["SchSerid"].stringValue
                            let userid = dic["UserSerID"].stringValue
                            let schname = dic["SchName"].stringValue
                            let doname = dic["imgurl"].stringValue
                            
                            let defaults = UserDefaults.standard
                            let user = UserPojo()
                            user.userphone = phone
                            user.userpassword = password
                            user.username = username
                            user.usertype = usertype
                            user.schid = schid
                            user.userid = userid
                            user.schname = schname
                            user.doname = doname
                            
                            defaults.set(user.userphone!, forKey: "userphone")
                            defaults.set(user.userpassword!, forKey: "password")
                            defaults.set(user.userid!, forKey: "userid")
                            defaults.set(user.username!, forKey: "username")
                            defaults.set(user.usertype!, forKey: "usertype")
                            defaults.set(user.schid!, forKey: "schid")
                            defaults.set(user.schname!, forKey: "schname")
                            defaults.set(user.doname!, forKey: "doname")
                            defaults.synchronize()
                            
                            let requestXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?><rss version=\"2.0\"><channel><t>37</t><sch>\(user.schid!)</sch><uid>\(user.userid!)</uid></channel></rss>"
                            let url = server + adminwebapppi
                            
                            HttpPostUTF(url, requestXML: requestXML, finished: { (data, result, error) in
                                if error == nil {
                                    
                                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                                    let rightArray = NSMutableArray()
                                    initLocationData()
                                    if array.count != 0 {
                                        rightArray.addObjects(from: array.arrayObject!)
                                    }
                                    setRightArray(rightArray)
                                    
                                    //+++++++++  1219-增加办公模块的数据   ++++++++++++++
                                    #if HSEDUMANAGE || TXEDUMANAGE
                                        
                                        let officeUrl = server + adminofficewebappapi
                                        let officeRequest = requestHeader + "1</t><schid>" + user.schid + "</schid><userid>" + user.userid + "</userid><usertype>T</usertype></channel></rss>"
                                        HttpPostUTF(officeUrl, requestXML: officeRequest, finished: { (data, result, error) in
                                            print("\(result!)")
                                            if error == nil {
                                                let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                                                let officeRightArray = NSMutableArray()
                                                
                                                if array.count != 0 {
                                                    officeRightArray.addObjects(from: array.arrayObject!)
                                                }
                                                
                                                setOfficeRightArray(officeRightArray)
                                                
                                                let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                                myDelegate.goToMain()
                                                
                                            }else {
                                                UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                                                self.hud.hide(true)
                                            }
                                            
                                            
                                        })
                                        
                                        
                                    #endif
                                    
                                
                                    #if EDUMANAGE
                                    let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                    myDelegate.goToMain()
                                    #endif
                                    
                                }else{
                                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                                    self.hud.hide(true)
                                }
                            })
                            
                        }
                    }
                    #elseif BELLSUPER || HSSUPER || TXSUPER
                        let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                        if array.count != 0 {
                            for i in 0..<array.count {
                                
                                let dic = array[i]
                                
                                let defaults = UserDefaults.standard
                                let user = UserPojo()
                                user.userphone = phone
                                user.userpassword = password
                                user.username = dic["TrueName"].stringValue
                                user.schid = dic["SchSerID"].stringValue
                                user.userid = dic["TeaSerID"].stringValue
                                user.UpperCode = dic["UpperCode"].stringValue
                                user.SupperType = dic["SuperType"].stringValue
                                
                                defaults.set(user.userphone!, forKey: "userphone")
                                defaults.set(user.userpassword!, forKey: "password")
                                defaults.set(user.userid!, forKey: "userid")
                                defaults.set(user.username!, forKey: "username")
                                defaults.set(user.schid!, forKey: "schid")
                                defaults.set(user.UpperCode, forKey: "UpperCode")
                                defaults.set(user.SupperType, forKey: "SupperType")
                                defaults.set("", forKey: "doname")
                                defaults.synchronize()

                                let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                                myDelegate.goToSuper()
                                
                            }
                    }
                    #endif
                }
                
            }else {
                UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                self.hud.hide(true)
            }
            
            
        
        })
        
    }
    
    //+++++++++  1219-增加办公模块的数据   ++++++++++++++
    
    func getOfficeRightData() {
       
        #if HSSUPER || TXSUPER
            
            let user = UserPojo()
            let officeUrl = server + adminofficewebappapi
            let officeRequest = requestHeader + "1</t><schid>" + user.schid! + "</schid><userid>" + user.userid! + "</userid><usertype>" + user.SupperType! + "</usertype></channel></rss>"
            HttpPostUTF(officeUrl, requestXML: officeRequest, finished: { (data, result, error) in
                print("\(result)")
                if error == nil {
                    let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                    let officeRightArray = NSMutableArray()
                    
                    if array.count != 0 {
                        officeRightArray.addObjects(from: array.arrayObject!)
                    }
                    
                    setOfficeRightArray(officeRightArray)
                    
                    let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
                    myDelegate.goToSuper()
                    
                }else {
                    UIAlertView.init(title: "错误提示", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "知道了").show()
                    self.hud.hide(true)
                }
                
                
            })
            
            
        #endif
        
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        phoneField.resignFirstResponder()
        passwordField.resignFirstResponder()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
